package com.yjhealth.libs.core.core.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.IdRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;

import com.qmuiteam.qmui.widget.QMUIWindowInsetLayout;
import com.yjhealth.libs.core.R;
import com.yjhealth.libs.core.core.CoreEvent;
import com.yjhealth.libs.core.net.utils.NetworkErrorUtil;
import com.yjhealth.libs.core.toast.ToastUtil;
import com.yjhealth.libs.core.view.loadview.LoadViewHelper;
import com.yjhealth.libs.core.view.titlebar.BsoftToolbar;
import com.yjhealth.libs.core.view.titlebar.config.TitleButtonConfig;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

/**
 * Created by chenkai on 2018/6/20.
 */

public abstract class CoreFragment extends CoreLoadViewFragment {
    /*Default*/
    /*Util*/
    /*Flag*/
    private Fragment currentFragment = new Fragment();
    /*View*/
    public View mainView;

    protected Toolbar yjhealthCoreToolbar;
    protected TextView yjhealthCoreTvTitle;

    //同yjhealthCoreToolbar AND yjhealthCoreTvTitle
    protected BsoftToolbar yjhealthCoreBosftToolbar;

    /**
     * 设置布局
     *
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    protected abstract View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState);

    /**
     * 初始化
     *
     * @param view
     * @param savedInstanceState
     */
    protected abstract void viewCreated(View view, @Nullable Bundle savedInstanceState);

    protected abstract void onRefreshView();


    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mainView = createView(inflater, container, savedInstanceState);
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        viewCreated(view, savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
    }




    @Override
    public void onDestroyView() {
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        super.onDestroyView();
    }

    @Override
    public void onDestroy() {
        dismissLoadingDialog();
        super.onDestroy();
    }


    /**
     * QMUI
     * fitsSystemWindows 问题，统一加上 QMUIWindowInsetLayout
     * @return
     */
    @Override
    protected View onCreateView() {
        QMUIWindowInsetLayout insert = new QMUIWindowInsetLayout(mainView.getContext());
        insert.addView(mainView);
        return insert;
    }


    protected <T extends View> T findViewById(@IdRes int id) {
        if (mainView == null) {
            return null;
        }
        return mainView.findViewById(id);
    }

    protected void initLayout() {
        initToolBar();
        super.intiLoadView(mainView);
    }


    protected void initToolBar() {
        //Toolbar
        yjhealthCoreTvTitle = mainView.findViewById(R.id.yjhealthCoreTvTitle);
        yjhealthCoreToolbar = mainView.findViewById(R.id.yjhealthCoreToolbar);
        if (yjhealthCoreToolbar != null) {
            yjhealthCoreToolbar.setTitle("");
            yjhealthCoreToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (getActivity() != null) {
                        getActivity().onBackPressed();
                    }
                }
            });
        }


        //BsoftToolbar
        yjhealthCoreBosftToolbar = findViewById(R.id.yjhealthCoreBosftToolbar);
        if (yjhealthCoreBosftToolbar != null) {
            yjhealthCoreBosftToolbar.setLisntener(new BsoftToolbar.OnBsoftToolbarLisntener() {
                @Override
                public void onItemClick(TitleButtonConfig config) {

                }

                @Override
                public void onBack() {
                    if (getActivity() != null) {
                        getActivity().onBackPressed();
                    }
                }

                @Override
                public void updateStatusBar() {

                }
            });
        }
    }

    //***************** show error toast **************
    public void showErrorToast(String errorType, String errorMsg) {
        if (TextUtils.equals(errorType, NetworkErrorUtil.ERROR_TYPE_SHOW)) {
            ToastUtil.toast(errorMsg);
        } else {
            ToastUtil.toast(LoadViewHelper.getMsgIdForError(errorType, 0));
        }
    }


    //******************* 切换fragment *********************
    public void switchFragment(Fragment targetFragment, @IdRes int resId) {
        FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
        if (!targetFragment.isAdded()) {
            if (currentFragment != null) {
                transaction.hide(currentFragment);
            }
            transaction.add(resId, targetFragment, targetFragment.getClass().getName());
        } else {
            transaction.hide(currentFragment).show(targetFragment);
        }
        currentFragment = targetFragment;
        transaction.commitAllowingStateLoss();
    }

    //******************* keyboard *********************
    public void hideKeyboard() {
        if (null != activity.getCurrentFocus()
                && null != activity.getCurrentFocus().getWindowToken()) {
            InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            // 隐藏软键盘
            if (imm != null) {
                imm.hideSoftInputFromWindow(activity.getWindow().getDecorView().getWindowToken(), 0);
            }
        }
    }

    public void showKeyboard() {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.showSoftInput(activity.getWindow().getDecorView(), InputMethodManager.SHOW_FORCED);
        }
    }

    public void showKeyboard(EditText editText) {
        InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.showSoftInputFromInputMethod(editText.getWindowToken(), 0);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, priority = 0)
    public void event(CoreEvent coreEvent) {

    }
}
